<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, computed, watch, getCurrentInstance } from "vue";
import { useUser } from "./utils/hook";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import type { FormItemProps } from "./utils/types";
import { delMenu } from "@/api/system/menu";

import More2Fill from "@iconify-icons/ri/more-2-fill";
import AddIcon from "@iconify-icons/ep/plus";
import EditIcon from "@iconify-icons/ep/edit";
import DelIcon from "@iconify-icons/ep/delete";
import HideIcon from "@iconify-icons/ep/hide";
import ExpandIcon from "./svg/expand.svg?component";
import UnExpandIcon from "./svg/unexpand.svg?component";

interface Tree {
  id: number;
  menuName: string;
  highlight?: boolean;
  children?: Tree[];
}

defineProps({
  treeLoading: Boolean,
  treeData: Array,
  tabType: Number
});

const emit = defineEmits(["tree-select", "load-tree"]);

const treeRef = ref();
const isExpand = ref(true);
const searchValue = ref("");
const highlightMap = ref({});
const { proxy } = getCurrentInstance();
const defaultProps = {
  children: "children",
  label: "menuName"
};
const buttonClass = computed(() => {
  return [
    "!h-[20px]",
    "!text-sm",
    "reset-margin",
    "!text-[var(--el-text-color-regular)]",
    "dark:!text-white",
    "dark:hover:!text-primary"
  ];
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.menuName.includes(value);
};

function nodeClick(value) {
  const nodeId = value.id;
  highlightMap.value[nodeId] = highlightMap.value[nodeId]?.highlight
    ? Object.assign({ id: nodeId }, highlightMap.value[nodeId], {
        highlight: false
      })
    : Object.assign({ id: nodeId }, highlightMap.value[nodeId], {
        highlight: true
      });
  Object.values(highlightMap.value).forEach((v: Tree) => {
    if (v.id !== nodeId) {
      v.highlight = false;
    }
  });
  emit(
    "tree-select",
    highlightMap.value[nodeId]?.highlight
      ? Object.assign({ ...value, selected: true })
      : Object.assign({ ...value, selected: false })
  );
}

/** 删除菜单 */
const delTree = async (treeData: FormItemProps) => {
  ElMessageBox.confirm(
    `确认要<strong>删除</strong><strong style='color:var(--el-color-primary)'>${
      treeData.menuName
    }</strong>菜单吗?`,
    "系统提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    }
  ).then(async () => {
    await delMenu(treeData.id);
    message("删除成功", {
      type: "success"
    });
    emit("load-tree");
  });
};

function toggleRowExpansionAll(status) {
  isExpand.value = status;
  const nodes = (proxy.$refs["treeRef"] as any).store._getAllNodes();
  for (let i = 0; i < nodes.length; i++) {
    nodes[i].expanded = status;
  }
}

/** 重置部门树状态（选中状态、搜索框值、树初始化） */
function onTreeReset() {
  highlightMap.value = {};
  searchValue.value = "";
  toggleRowExpansionAll(true);
}

watch(searchValue, val => {
  treeRef.value!.filter(val);
});

/** 设置当前选择的tree */
function setCurrentKey(treeId: number) {
  highlightMap.value[treeId] = {
    id: treeId,
    highlight: true
  };
}

defineExpose({ onTreeReset, setCurrentKey });

const { openDialog } = useUser(treeRef);
</script>

<template>
  <div
    v-loading="treeLoading"
    class="h-full bg-bg_color overflow-hidden relative"
    :style="{ minHeight: `calc(100vh - 170px)` }"
  >
    <div class="flex items-center justify-between h-[50px] ml-2 mr-2">
      <div class="text-sm">{{ tabType == 1 ? "平台" : "门店" }}菜单</div>
      <el-button type="primary" size="small" @click="openDialog('新增', 1)"
        >新增一级菜单</el-button
      >
    </div>

    <el-divider />
    <div class="flex items-center h-[42px] ml-2 mr-2">
      <el-input
        v-model="searchValue"
        size="small"
        placeholder="请输入菜单名称"
        clearable
      >
        <template #suffix>
          <el-icon class="el-input__icon">
            <IconifyIconOffline
              v-show="searchValue.length === 0"
              icon="ri:search-line"
            />
          </el-icon>
        </template>
      </el-input>
      <el-dropdown :hide-on-click="false">
        <IconifyIconOffline
          class="w-[28px] cursor-pointer"
          width="18px"
          :icon="More2Fill"
        />
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>
              <el-button
                :class="buttonClass"
                link
                type="primary"
                :icon="useRenderIcon(isExpand ? ExpandIcon : UnExpandIcon)"
                @click="toggleRowExpansionAll(isExpand ? false : true)"
              >
                {{ isExpand ? "折叠全部" : "展开全部" }}
              </el-button>
            </el-dropdown-item>
            <!-- <el-dropdown-item>
              <el-button
                :class="buttonClass"
                link
                type="primary"
                :icon="useRenderIcon(Reset)"
                @click="onTreeReset"
              >
                重置状态
              </el-button>
            </el-dropdown-item> -->
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <el-scrollbar height="calc(90vh - 166px)" class="pl-[5px]">
      <el-tree
        ref="treeRef"
        :data="treeData"
        node-key="id"
        size="small"
        :indent="10"
        :props="defaultProps"
        default-expand-all
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="nodeClick"
      >
        <template #default="{ node, data }">
          <div
            :class="[
              'rounded',
              'flex',
              'items-center',
              'select-none',
              'hover:text-primary',
              '!pl-[5px]',
              '!ml-[-5px]',
              'h-[25px]',
              'pr-2',
              searchValue.trim().length > 0 &&
                node.label.includes(searchValue) &&
                'text-red-500',
              highlightMap[data.id]?.highlight ? 'dark:text-primary' : ''
            ]"
            :style="{
              color: highlightMap[data.id]?.highlight
                ? 'var(--el-color-primary)'
                : '',
              background: highlightMap[data.id]?.highlight
                ? 'var(--el-color-primary-light-7)'
                : 'transparent'
            }"
          >
            <!-- 菜单图标 -->
            <component
              :is="useRenderIcon(data.menuIcon)"
              v-if="data.menuIcon"
            />

            <!-- 菜单名称 -->
            <div
              class="!w-[140px] !truncate pl-[5px] flex items-center"
              :title="node.label"
            >
              <div class="mr-[5px]">{{ node.label }}</div>
              <IconifyIconOffline
                v-if="data.menuStatus == 2"
                :icon="HideIcon"
              />
            </div>

            <!-- 操作图标 -->
            <template v-if="highlightMap[data.id]?.highlight">
              <IconifyIconOffline
                :icon="AddIcon"
                @click.stop="openDialog('新增', 1, { ...data })"
              />
              <IconifyIconOffline
                :icon="EditIcon"
                class="ml-2"
                @click.stop="openDialog('编辑', 1, data)"
              />
              <IconifyIconOffline
                v-if="node.isLeaf"
                :icon="DelIcon"
                class="text-red-500 ml-2"
                @click.stop="delTree(data)"
              />
            </template>
          </div>
        </template>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-divider) {
  margin: 0;
}

:deep(.el-tree) {
  --el-tree-node-hover-bg-color: transparent;
}
</style>
